<template>
  <el-dialog

    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    :close-on-click-modal="false"
    @close="shutdown"
    @open="openDialog"
  >
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="isLoading">
      <el-checkbox
        v-for="item in roleList"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assignRole">确定</el-button>
      <el-button size="small" @click="shutdown">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getsettingApi } from '@/api/setting'
import { gettouxiang } from '@/api/user'
import { assignRolesApi } from '@/api/emplyees'
export default {
  name: 'AssignRole',
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 请求列表的两个参数
      form: {
        page: 1,
        pagesize: 10
      },
      // 存放请求回来的数据
      roleList: [],
      // 存放选框是否选中
      roleIds: [],
      // 转圈圈的参数
      isLoading: false
    }
  },
  methods: {
    // 关闭弹窗
    shutdown() {
      this.$emit('update:showRoleDialog', false)
    },
    // 获取列表的角色
    async getRoleList() {
      const { data: { rows }} = await getsettingApi(this.form)
      // console.log(rows)
      this.roleList = rows
    },
    // 获取每个角色都有什么权限并且赋值给roleids 回显数据
    async getBaseUserInfo() {
      const { data: { roleIds }} = await gettouxiang(this.userId)
      this.roleIds = roleIds
    },
    // 同时发起两个请求 在弹窗出现的时候
    openDialog() {
      this.isLoading = true
      Promise.all([this.getRoleList(), this.getBaseUserInfo()]).then(() => {
        this.isLoading = false
      })
    },
    // 点击确定的时候修改角色信息
    async assignRole() {
      await assignRolesApi({ id: this.userId, roleIds: this.roleIds })
      this.shutdown()
      this.$message.success('恭喜，角色分配成功')
    }

  }
}
</script>
